<script lang="ts" setup>
import { getCurrentInstance, ref, inject, watch } from 'vue'
import {
  onHide,
  onLoad,
  onPageScroll,
  onReady,
  onShow,
  onUnload,
} from '@dcloudio/uni-app'
import { useScrollUpdownBottomContent } from '@/hooks'
import TnPopup from '@tuniao/tnui-vue3-uniapp/components/popup/src/popup.vue'
import { useSubPage } from './composables'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import { privacyPopup } from '@/components/privacyPopup'
import { useUserStore } from '@/stores'
import {
  delPlansApi,
  getGradesApi,
  getPlanInfoAPi,
  uploadSettingApi,
} from '@/services/api'
import boolean from '@tuniao/tnui-vue3-uniapp/libs/async-validator/validator/boolean'
import TnLineProgress from '@tuniao/tnui-vue3-uniapp/components/line-progress/src/line-progress.vue'
import { notActiveBar } from '@/components/not-active-bar'
import TnSwiper from '@tuniao/tnui-vue3-uniapp/components/swiper/src/swiper.vue'
const subsectionValue = ref(0)
const scenseType = ref(1)
const needDay = ref(0)
const planDetail = ref({} as any)
const notActiveBar = ref(null)
const userStore = useUserStore()
const currentSwiperIndex = ref()
const soundPlaying = ref(false)
const ifBindBook = ref(false)
// 轮播图数据
const swiperData = [
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/banner/%E7%94%B7%E5%A3%B0-%E7%BA%AF%E8%89%B2-%E8%83%8C%E6%99%AF-banner.png',
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/banner/03.png',
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/banner/01.png',
]
// 静态数字人
const jPeople = [
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/gif/man_matting.png',
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/gif/woman_matting.png',
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/gif/kid_matting.png',
]
//动态数字人
const dPeople = [
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/gif/man_matting.gif',
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/gif/woman_matting.gif',
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/gif/kid_matting.gif',
]
//声音
const sound = [
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/%E6%95%B0%E5%AD%97%E4%BA%BA/%E6%95%B0%E5%AD%97%E4%BA%BA%E8%80%81%E5%B8%88Andrew%2Bmale.mp3',
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/%E6%95%B0%E5%AD%97%E4%BA%BA/%E6%95%B0%E5%AD%97%E4%BA%BA%E8%80%81Jenny%2Bfemale.mp3',
  'https://aia-upload-sz.oss-cn-shenzhen.aliyuncs.com/AI_xyw_learning/%E6%95%B0%E5%AD%97%E4%BA%BA/%E6%95%B0%E5%AD%97%E4%BA%BA%E8%80%81%E5%B8%88Ana%2Bchildren.mp3',
]
const toSetPlan = () => {
  if (ifBindBook.value) {
    uni.navigateTo({
      url: `/home-page/setPlan/index?data=${encodeURIComponent(JSON.stringify(planDetail.value))}&ifFinish=${0}`,
    })
  } else {
    uni.showToast({ title: '请先绑定教材', icon: 'none' })
  }
}
const toListenPage = async () => {
  if (planDetail.value.morningStudyInfo.planId) {
    console.log('999999')
    //已经完成该书的计划，清楚计划重新制定
    if (planDetail.value.hadLearnSum == planDetail.value.lessonSum) {
      console.log('888')
      uni.showModal({
        title: '已学完',
        content: `恭喜您已完成《${planDetail.value.title}》的${subsectionValue.value == 0 ? '单词' : subsectionValue.value == 1 ? '句子' : subsectionValue.value == 2 ? '课文' : ''}早晚听!`,
        confirmText: '重新制定',
        cancelText: '知道了',
        success: function (res) {
          if (res.confirm) {
            console.log('制定计划重新学')
            uni.navigateTo({
              url: `/home-page/setPlan/index?data=${encodeURIComponent(JSON.stringify(planDetail.value))}&ifFinish=${1}`,
            })
          } else if (res.cancel) {
            console.log('知道了')
          }
        },
      })
    } else {
      const mType = showMOrE()
      if (mType == 1) {
        //早上
        uni.navigateTo({
          url: `/pages/listen/index?learnType=${subsectionValue.value + 1}&scenseType=${scenseType.value}&planId=${planDetail.value.morningStudyInfo.planId}`,
        })
      } else {
        //晚上
        uni.navigateTo({
          url: `/pages/listen/index?learnType=${subsectionValue.value + 1}&scenseType=${scenseType.value}&planId=${planDetail.value.nightStudyInfo.planId}`,
        })
      }
    }
  } else {
    uni.showModal({
      title: '制定计划',
      content: `请前往制定${subsectionValue.value == 0 ? '单词' : subsectionValue.value == 1 ? '句子' : subsectionValue.value == 2 ? '课文' : ''}早晚听计划`,
      confirmText: '前往制定',
      cancelText: '暂不制定',
      success: function (res) {
        if (res.confirm) {
          console.log('制定计划重新学')
          uni.navigateTo({
            url: `/home-page/setPlan/index?data=${encodeURIComponent(JSON.stringify(planDetail.value))}&ifFinish=${0}`,
          })
        } else if (res.cancel) {
          console.log('知道了')
        }
      },
    })
  }
}
//判断是早上还是晚上
const showMOrE = () => {
  const mTime = planDetail.value.morningStudyInfo.learnTime
  const eTime = planDetail.value.nightStudyInfo.learnTime
  if (
    getNowTime() >= getTimeStamp(mTime) &&
    getNowTime() <= getTimeStamp(eTime)
  ) {
    //早上
    console.log('早上')
    return 1
  } else {
    // 晚上
    console.log('晚上')
    return 2
  }
}
//将时间8:00转为时间戳
const getTimeStamp = (time) => {
  const arr = time.split(':')
  const number = arr[0] * 60 * 60 + arr[1] * 60
  return number
}
//获取当前时间
const getNowTime = () => {
  console.log('9999999999')
  console.log(new Date().getTime(), 'ppppp')
  const date = new Date()
  const hours = date.getHours()
  const minutes = date.getMinutes()
  console.log(`${hours}:${minutes}`)
  return hours * 60 * 60 + minutes * 60
}

const tapChange = async (index) => {
  console.log(subsectionValue.value)
  if (ifBindBook.value) {
    await getPlan()
    if (planDetail.value.planPerDayNum != 0) {
      needDay.value = Math.ceil(
        (planDetail.value.lessonSum - planDetail.value.hadLearnSum) /
          planDetail.value.planPerDayNum
      )
    } else {
      needDay.value = 0
    }
  } else {
    uni.showToast({ title: '请先绑定教材', icon: 'none' })
  }
}
const fresh = async () => {
  console.log('freshfreshfreshfresh')
  if (notActiveBar.value) {
    notActiveBar.value.show()
  }
  if (userStore.getBookId !== '') {
    console.log('777', currentSwiperIndex.value)
    ifBindBook.value = true
    await getPlan()
    if (planDetail.value.planPerDayNum != 0) {
      needDay.value = Math.ceil(
        (planDetail.value.lessonSum - planDetail.value.hadLearnSum) /
          planDetail.value.planPerDayNum
      )
    } else {
      needDay.value = 0
    }
  } else {
    ifBindBook.value = false
  }
  // await getPlan()
  // if (planDetail.value.planPerDayNum != 0) {
  //   needDay.value = Math.ceil(
  //     (planDetail.value.lessonSum - planDetail.value.hadLearnSum) /
  //       planDetail.value.planPerDayNum
  //   )
  // } else {
  //   needDay.value = 0
  // }
}
onShow(async () => {
  if (userStore.getIfOnLunch == true) {
    console.log('初始化之后onShow的内容')
    if (notActiveBar.value) {
      notActiveBar.value.show()
    }
    if (userStore.getBookId !== '') {
      console.log('777', currentSwiperIndex.value)
      ifBindBook.value = true
      await getPlan()
      if (planDetail.value.planPerDayNum != 0) {
        needDay.value = Math.ceil(
          (planDetail.value.lessonSum - planDetail.value.hadLearnSum) /
            planDetail.value.planPerDayNum
        )
      } else {
        needDay.value = 0
      }
    } else {
      ifBindBook.value = false
    }
  }
})
onHide(() => {
  console.log('onHide关闭页面')
  console.log('关闭页面')
  if (promptSound) {
    promptSound.stop()
    soundPlaying.value = false
    // promptSound = null
  }
})
onUnload(() => {})
watch(
  () => userStore.getIfOnLunch,
  async (val) => {
    console.log('初始化加载onShow的内容')
    if (notActiveBar.value) {
      notActiveBar.value.show()
    }
    setTimeout(() => {
      currentSwiperIndex.value = userStore.getSound_people - 1
    }, 0)
    if (userStore.getBookId !== '') {
      ifBindBook.value = true
      // playSound()
      await getPlan()
      if (planDetail.value.planPerDayNum != 0) {
        needDay.value = Math.ceil(
          (planDetail.value.lessonSum - planDetail.value.hadLearnSum) /
            planDetail.value.planPerDayNum
        )
      } else {
        needDay.value = 0
      }
      console.log('初始化加载onShow的内容', currentSwiperIndex.value)
    } else {
      ifBindBook.value = false
    }
  }
)
const getPlan = async () => {
  console.log('userStore.getBookId', userStore.getBookId)
  const params = {
    bookId: userStore.getBookId,
    learnType: subsectionValue.value + 1,
    scenseType: scenseType.value,
  }
  const data = await getPlanInfoAPi(params)
  if (data.code === 200) {
    planDetail.value = data.data
    planDetail.value.learnType = subsectionValue.value + 1
    planDetail.value.scenseType = scenseType.value
    console.log(planDetail.value)
  }
}
const changePeople = async (e) => {
  console.log('changePeople', e)
  console.log('currentSwiperIndex.value', e)
  if (currentSwiperIndex.value !== userStore.getSound_people - 1) {
    const data = await uploadSettingApi({
      pronunciationType: e + 1,
    })
    if (data.code === 200) {
      userStore.setSoundPeople(e + 1)
      soundPlaying.value = false
      playSound()
    } else {
      uni.showToast({
        title: '设置失败',
        icon: 'none',
      })
    }
  }

  // if (currentSwiperIndex.value !== e) {
  //   const data = await uploadSettingApi({
  //     pronunciationType: e + 1,
  //   })
  //   if (data.code === 200) {
  //     userStore.setSoundPeople(e + 1)
  //     soundPlaying.value = false
  //     playSound()
  //   } else {
  //     uni.showToast({
  //       title: '设置失败',
  //       icon: 'none',
  //     })
  //   }
  // }
}
const changeSpeed = async () => {
  const data = await uploadSettingApi({
    playSpeed: speed.value,
  })
  if (data.code === 200) {
    userStore.setSoundSpeed(speed.value)
  } else {
    uni.showToast({
      title: '设置失败',
      icon: 'none',
    })
    speed.value = userStore.getSound_speed
  }
}
var promptSound = null
//播放mp3
const playSound = () => {
  if (promptSound) {
    console.log('播放中停止播放')
    promptSound.stop()
    promptSound = null
  }
  promptSound = uni.createInnerAudioContext()
  promptSound.src = sound[currentSwiperIndex.value]
  console.log('开始播放')
  promptSound.play() //执行播放
  promptSound.onPlay(() => {
    soundPlaying.value = true
  })
  promptSound.onTimeUpdate(() => {
    console.log('播放中')
    soundPlaying.value = true
  })
  promptSound.onEnded(() => {
    promptSound.stop()
    promptSound = null
    soundPlaying.value = false
    console.log('播放结束', soundPlaying.value)
  })
}
</script>

<template>
  <view class="contain">
    <view class="swiper-container">
      <TnSwiper
        v-model="currentSwiperIndex"
        :data="swiperData"
        width="100%"
        height="384"
        @change="changePeople"
      >
        <template #default="{ data }">
          <view class="swiper-data">
            <image class="image_bg" :src="data" mode="widthFix" />
            <image
              class="image_people"
              :src="
                soundPlaying
                  ? dPeople[currentSwiperIndex]
                  : jPeople[currentSwiperIndex]
              "
              mode="widthFix"
            />
          </view>
        </template>
      </TnSwiper>
    </view>
    <!-- <view class="top_banner">
      <image
        class=""
        src="../../static/images/b1.png"
        mode="widthFix"
        lazy-load="false"
        binderror=""
        bindload=""
      />
    </view> -->
    <view class="main">
      <TnSubsection
        v-model="subsectionValue"
        active-color="#5155E6"
        @change="tapChange"
      >
        <TnSubsectionItem title="单词" />
        <TnSubsectionItem title="句子" />
        <TnSubsectionItem title="课文" />
      </TnSubsection>
      <view class="main_box">
        <view class="main_box_list">
          <view class="bookStyleBox">
            <view class="bookImg">
              <image :src="planDetail.bookUrl" v-if="ifBindBook" />
              <image v-else src="../../static/images/n1.png" />
            </view>
            <view class="right_box">
              <view class="title_Line">
                <view class="title">
                  {{ ifBindBook ? planDetail.title : '请先绑定教材' }}
                </view>
                <view class="changeBox" @tap="toSetPlan">
                  <text class=""> 修改 </text>
                  <TnIcon name="right" />
                </view>
              </view>
              <view class="progress">
                <TnLineProgress
                  :percent="
                    (planDetail.hadLearnSum / planDetail.lessonSum) * 100
                  "
                  active-color="#3388FF"
                  height="10"
                />
              </view>
              <view class="bottom_box">
                <view class="text_number">
                  {{
                    ifBindBook
                      ? planDetail.hadLearnSum + '/' + planDetail.lessonSum
                      : '0/0'
                  }}
                </view>
                <view class="right_text">
                  剩余{{ ifBindBook ? needDay : 0 }}天
                </view>
              </view>
            </view>
          </view>
          <view class="tip_text"> 今日计划 </view>
          <view class="type_box_line">
            <view class="type_box">
              <view class="text"> 早上已听 </view>
              <view class="number_box">
                <text class="left_text">
                  {{
                    ifBindBook
                      ? planDetail.morningStudyInfo.todayHadLearnSum
                      : 0
                  }}
                </text>
                <text class="right_text">
                  /{{
                    ifBindBook
                      ? planDetail.morningStudyInfo.morningLearnSum
                      : 0
                  }}个
                </text>
              </view>
            </view>
            <view class="day_box">
              <view class="text"> 晚上已听 </view>
              <view class="number_box">
                <text class="left_text">
                  {{
                    ifBindBook ? planDetail.nightStudyInfo.todayHadLearnSum : 0
                  }}
                </text>
                <text class="right_text">
                  /{{
                    ifBindBook ? planDetail.nightStudyInfo.nightLearnSum : 0
                  }}个
                </text>
              </view>
            </view>
          </view>
        </view>
        <TnButton
          class="btn"
          bg-color="#5155E6"
          text-color="#fff"
          width="100%"
          height="100rpx"
          font-size="40rpx"
          @tap="toListenPage"
          v-if="ifBindBook"
          >{{
            planDetail.morningStudyInfo.todayHadLearnSum > 0 ||
            planDetail.nightStudyInfo.todayHadLearnSum > 0
              ? '继续听'
              : '开始听'
          }}</TnButton
        >
        <!-- <TnButton
          class="btn"
          bg-color="#5155E6"
          text-color="#fff"
          width="100%"
          height="100rpx"
          font-size="40rpx"
          @tap="toListenPage"
          v-if="
            ifBindBook &&
            planDetail.morningStudyInfo.planId &&
            planDetail.nightStudyInfo.planId
          "
          >{{
            planDetail.morningStudyInfo.todayHadLearnSum > 0 ||
            planDetail.nightStudyInfo.todayHadLearnSum > 0
              ? '继续听'
              : '开始听'
          }}</TnButton
        > -->
      </view>
    </view>
  </view>
  <notActiveBar ref="notActiveBar" height="0" @fresh="fresh" />
  <!-- 隐私授权框 -->
  <privacyPopup></privacyPopup>
</template>

<style lang="scss" scoped>
.contain {
  width: 100%;
  .top_banner {
    width: 100%;
    image {
      width: 100%;
    }
  }
  .main {
    padding: 20rpx 32rpx;
  }
  .main_box {
    width: 100%;
    .main_box_list {
      width: 100%;
      background: #fff;
      border-radius: 20rpx;
      padding: 32rpx 32rpx 60rpx;
      margin-top: 32rpx;
      margin-bottom: 50rpx;
      .bookStyleBox {
        width: 100%;
        display: flex;
        padding-bottom: 32rpx;
        border-bottom: 2rpx solid #bbbbbb;
        .bookImg {
          width: 120rpx;
          height: 180rpx;
          object-fit: contain;
          margin-right: 20rpx;
        }
        .right_box {
          flex: 1;
          .title_Line {
            width: 100%;
            display: flex;
            justify-content: space-between;
            .title {
              font-size: 28rpx;
              color: #101010;
              font-weight: bold;
            }
            .changeBox {
              color: #6c6c6c;
              font-size: 26rpx;
            }
          }
          .progress {
            margin: 38rpx 0;
          }
          .bottom_box {
            display: flex;
            justify-content: space-between;
            align-items: center;
            .text_number {
              color: #6c6c6c;
              font-size: 26rpx;
            }
            .right_text {
              color: #101010;
              font-size: 28rpx;
              font-weight: bold;
            }
          }
        }
      }
      .tip_text {
        height: 90rpx;
        line-height: 90rpx;
        color: #101010;
        font-size: 32rpx;
        font-weight: bold;
      }
      .type_box_line {
        display: flex;
        justify-content: space-between;
        padding: 0 10rpx;
        .type_box {
          width: 50%;
          padding-left: 20rpx;
          .text {
            color: #101010;
            font-size: 28rpx;
            font-weight: bold;
            margin: 10rpx 0 16rpx;
          }
          .number_box {
            .left_text {
              color: #101010;
              font-size: 80rpx;
              font-weight: bold;
              font-style: oblique;
            }
            .right_text {
              color: #6c6c6c;
              font-size: 40rpx;
            }
          }
        }
        .day_box {
          width: 50%;
          display: flex;
          flex-direction: column;
          align-items: center;
          .text {
            color: #101010;
            font-size: 28rpx;
            font-weight: bold;
            margin: 10rpx 0 16rpx;
          }
          .number_box {
            .left_text {
              color: #101010;
              font-size: 80rpx;
              font-weight: bold;
              font-style: oblique;
            }
            .right_text {
              color: #6c6c6c;
              font-size: 40rpx;
            }
          }
        }
      }
    }
  }
}
.swiper-container {
  width: 100%;
  height: auto;

  .swiper-data {
    width: 100%;
    height: 100%;
    border-radius: 30rpx;
    position: relative;

    .image_bg {
      width: 100%;
      border-radius: inherit;
    }
    .image_people {
      width: 32%;
      position: absolute;
      bottom: 0;
      right: 50rpx;
    }
  }
}
</style>
